package com.hiv.controller.admin;

import com.hiv.common.BaseController;
import com.hiv.common.Constants;
import com.hiv.common.WebResponse;
import com.hiv.common.param.AdminLogonParam;
import com.hiv.mapper.domain.Admin;
import com.hiv.service.AdminAccountService;
import com.hiv.utils.CookieUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 管理员Controller
 *
 * @author zhanghong
 * @date 2022-07-09
 */
@RestController
@RequestMapping("/admin/account")
@Api(value = "管理员登录模块", tags = {"【管理端】管理员登录模块"})
public class AdminAccountController extends BaseController {

    @Autowired
    private AdminAccountService adminAccountService;

    @ApiOperation(value = "登录", httpMethod = "POST")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "success")})
    @PostMapping("/login")
    public WebResponse<Admin> login(HttpServletRequest request, HttpServletResponse response, @RequestBody AdminLogonParam adminLogonParam) {
        Admin admin = adminAccountService.findAdmin(adminLogonParam.getAccount(), adminLogonParam.getPassword());
        admin.setPassword(null);
        request.getSession().setAttribute(Constants.LOGIN_ADMIN, admin);
        response.addCookie(new Cookie(Constants.SESSIONID, CookieUtil.getValue(request, Constants.SESSIONID)));
        return WebResponse.build(admin);
    }

    @ApiOperation(value = "登出", httpMethod = "POST")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "success")})
    @RequestMapping("/logout")
    public WebResponse logout(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().removeAttribute(Constants.LOGIN_ADMIN);
        return new WebResponse(true);
    }

    @ApiOperation(value = "获取个人信息", httpMethod = "POST")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "success")})
    @PostMapping("/me")
    public WebResponse<Admin> me(HttpServletRequest request, HttpServletResponse response) {
        Admin admin = validAdminLoginAndGet(request);
        return WebResponse.build(admin);
    }
}
